package com.house.web.controller;


import java.io.FileOutputStream;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import com.house.biz.HouseBiz;
import com.house.biz.PhotoBiz;
import com.house.entity.House;
import com.house.entity.Photo;
import com.house.entity.User;

@Controller
public class AddHouseController {
	@Autowired
	private HouseBiz houseBiz;
	@Autowired
	private PhotoBiz photoBiz;
	
	@RequestMapping("/let")
	public String let(){
		return "let";
	}
	
	@RequestMapping(value="/addHouse",method=RequestMethod.POST)
	public String addHouse(House house,Model model,HttpServletRequest request){
		User user=(User) request.getSession().getAttribute("user");
		
		house.setUpdateTime(new Date());
		house.setState(1);
		house.setUser(user);
		houseBiz.addHouse(house);
		
		model.addAttribute("houseId",house.getId());
		
		return "let_addPhoto";
	}
	
	@RequestMapping("/addPhoto")
	public String addPhoto(Photo photo,MultipartFile coverImages,HttpServletRequest request){
	
		if(coverImages!=null && !coverImages.isEmpty()){
			String path=request.getSession().getServletContext().getRealPath("CoverImages");
			String fileName=path+"\\"+photo.getHourse().getId()+".jpg";
			System.out.println(fileName);
			photo.setFileName(photo.getHourse().getId()+".jpg");
			try {
				FileOutputStream fos=new FileOutputStream(fileName);
				fos.write(coverImages.getBytes());
				fos.close();
				photoBiz.addPhoto(photo);
				System.out.println("上传成功。。。");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return "redirect:index";
	}
}
